import {AfterViewInit, Component, OnInit} from '@angular/core';
import {TimelineService} from "./timeline.service";

@Component({
  selector: 'consoler-timeline',
  templateUrl: './timeline.component.html',
  styleUrls: ['./timeline.component.scss'],
  providers: [TimelineService]
})
export class TimelineComponent implements OnInit, AfterViewInit {

  private $ = window['$'];

  public loading: boolean;

  public listData = [];

  public modalClass = {};

  public modalModel = {
    title: "",
    time: "",
    repeat: false,
    remark: "",
    participant: ""
  };


  constructor(private timelineService: TimelineService) {
  }

  ngOnInit() {
    this.updateTimeLine();
    this.$('#repeat').iCheck({
      checkboxClass: 'icheckbox_square-blue',
      radioClass: 'iradio_square-blue',
      increaseArea: '20%'
    });
    this.$("#participant").select2();
    this.$("#time").timepicker({
      maxHours: 24,
      showMeridian: false
    });
  }

  ngAfterViewInit(): void {
    this.$('#repeat')
      .on("ifChecked", () => {
        this.modalModel.repeat = true;
      })
      .on("ifUnchecked", () => {
        this.modalModel.repeat = false;
      });
  }

  public updateTimeLine() {
    this.loading = true;
    return this.timelineService.getTimelineData().subscribe(data => {
      this.listData = data;
      this.loading = false;
    });
  }

  public popModal() {
    this.modalClass = {
      in: true,
      show: true
    };
  }

  public closeModal() {
    this.modalClass = {
      in: false,
      show: false
    };
    this.resetModalModel();
  }

  public addTimelineData() {
    const that = this;
    this.timelineService.addTimeLineData({
      time: that.$("#time").val().trim(),
      matter: that.modalModel.title.trim(),
      repeat: that.modalModel.repeat,
      remark: that.modalModel.remark.trim(),
      participant: that.$("#participant").select2("val").join(",")
    });
    this.closeModal();
    this.updateTimeLine();
  }

  private resetModalModel() {
    this.modalModel = {
      title: "",
      time: "",
      repeat: false,
      remark: "",
      participant: ""
    };
    this.$("#repeat").iCheck("uncheck");
    this.$("#time").val("");
    this.$("#participant").select2("val", [""]);
  }

}
